package com.csnf.dao.impl;

import com.csnf.dao.ICourseDao;
import com.csnf.entity.course;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ICourseDaoImpl implements ICourseDao {
    @Override
    public List<course> getAllCourse() throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<course> courses = sqlSession.selectList("getAllCourse");
        sqlSession.close();
        return courses;
    }

    @Override
    public course getCourseById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        course course = sqlSession.selectOne("getCourseById", id);
        sqlSession.close();
        return course;
    }

    @Override
    public void addCourse(course course) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.insert("addCourse", course);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteCourse(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.delete("deleteCourse", id);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public List<course> getCourseByName(String name) throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<course> courses = sqlSession.selectList("getCourseByName", name);
        sqlSession.close();
        return courses;
    }


    private static SqlSession getSqlSession() throws IOException {
        String path = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourceAsStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        return sqlSession;
    }
}
